﻿using ApiLib.AppStart;
using ApiLib.Common.Attributes;
using ApiLib.Helpers;
using ApiLib.Utils;
using Microsoft.AspNetCore.Mvc.Controllers;
using SqlSugar;

namespace ApiLib.Models;

/// <summary>
/// 基础用户信息
/// </summary>
[Tenant(GlobalConstants.MainDbConfigId), SugarTable("sys_userinfo")]
[Excel("用户表")]
public class SysUserinfo : IBaseUser
{
    /// <summary>
    ///  
    ///</summary>
    [SugarColumn(ColumnName = "id", IsPrimaryKey = true, IsIdentity = true)]
    [Excel(IsIgnore = true)]
    public int Id { get; set; }

    /// <summary>
    /// 用户名 
    ///</summary>
    [SugarColumn(ColumnName = "username")]
    [Excel("用户名")]
    public string Username { get; set; }

    /// <summary>
    /// 密码 
    ///</summary>
    [SugarColumn(ColumnName = "password")]
    [Excel("密码")]
    public string Password { get; set; }

    /// <summary>
    /// 角色 
    ///</summary>
    [SugarColumn(ColumnName = "role")]
    [Excel("角色")]
    public string Role { get; set; }

    /// <summary>
    /// 权限 
    ///</summary>
    [SugarColumn(ColumnName = "permissions")]
    [Excel("权限")]
    public string Permissions { get; set; }
    /// <summary>
    /// 头像 
    ///</summary>
    [SugarColumn(ColumnName = "head_picture")]
    public string HeadPicture { get; set; }

    /// <summary>
    /// 性别 
    ///</summary>
    [SugarColumn(ColumnName = "sex")]
    public string Sex { get; set; } = "男";
    
    /// <summary>
    /// 权限，不从OA同步
    /// </summary>
    [SugarColumn(IsIgnore = true)]
    [Excel(IsIgnore = true)]
    public HashSet<string> PermissionsSet { get; set; }

    /// <summary>
    /// 权限，不从OA同步
    /// </summary>
    [SugarColumn(IsIgnore = true)]
    [Excel(IsIgnore = true)]
    public HashSet<string> RolesSet { get; set; }
    
    /// <summary>
    /// 角色名称
    /// </summary>
    [SugarColumn(IsIgnore = true)]
    [Excel("职务")]
    public string RoleNames { get; set; }

    /// <summary>
    /// 获取用户ID
    /// </summary>
    /// <returns></returns>
    public string GetSid()
    {
        return Id.ToString();
    }

    /// <summary>
    /// 获取用户名
    /// </summary>
    /// <returns></returns>
    public string GetName()
    {
        return Username;
    }

    /// <summary>
    /// 获取角色
    /// </summary>
    /// <returns></returns>
    public virtual HashSet<string>? GetRoles()
    {
        if (!string.IsNullOrEmpty(Role))
        {
            return Role.Split(",").ToHashSet();
        }

        return default;
    }

    /// <summary>
    /// 初始化权限
    /// </summary>
    public virtual void InitPermissions()
    {
        if (GlobalConfig.BaseAuthorization==null || !GlobalConfig.BaseAuthorization.InitPermission)
        {
            return;
        }
        if (!string.IsNullOrEmpty(Permissions))
        {
            PermissionsSet = Permissions.Split(",").ToHashSet();
        }
        PermissionsSet ??= [];
        RolesSet ??= [];

        var roles = DbHelper.Db.Queryable<SysRole>()
            .InnerJoin<SysRoleUser>((role, user) => role.Id == user.RoleId)
            .Where((role, user) => user.Id == Id)
            .Select((role, user) => role)
            .ToList();
        if (IsSuperAdmin())
        {
            PermissionsSet=GlobalConfig.BaseAuthorization.GetAllPermissions();
        }
        else
        {
            foreach (var role in roles)
            {
                if (!string.IsNullOrEmpty(role.Permissions))
                {
                    PermissionsSet.AddAll(role.Permissions.Split(","));
                }
            }
        }

        RolesSet = roles.Select(r => r.Id.ToString()).ToHashSet();
        RoleNames = string.Join(",", roles.Select(r => r.Name));
    }

    /// <summary>
    /// 获取权限
    /// </summary>
    /// <returns></returns>
    public virtual HashSet<string>? GetPermissions()
    {
        if (!string.IsNullOrEmpty(Permissions))
        {
            return Permissions.Split(",").ToHashSet();
        }
        return default;
    }

    /// <summary>
    /// 是否拥有访问权限
    /// </summary>
    /// <param name="descriptor"></param>
    /// <param name="attribute"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public virtual bool HasPermission(ControllerActionDescriptor descriptor, PermissionAttribute? attribute = null)
    {
        return true;
    }

    /// <summary>
    /// 是否超级管理员
    /// </summary>
    /// <returns></returns>
    public virtual bool IsSuperAdmin()
    {
        return false;
    }
}